//
//  WordCount.m
//  Word Count
//
//  Created by Dethe Elza on 20/12/06.
//  Copyright 2006 Living Code Enterprises. All rights reserved.
//

#import "WordCount.h"


@implementation LCWordCount

+ (id)sharedInstance{

    static LCWordCount* plugin = nil;

    if (plugin == nil){
        plugin = [[LCWordCount alloc] init];
    }
    return plugin;
}

+ (void)initialize{
    NSMenu * formatMenu =  [[[NSApp mainMenu] itemWithTitle: @"Format"] submenu];
    [formatMenu addItem: [NSMenuItem separatorItem]];
    NSMenuItem * item = [formatMenu addItemWithTitle: @"Count Words" action: @selector(wordcount:) keyEquivalent: @"l"];
    [item setTarget: [LCWordCount sharedInstance]];
    // Turn off "smart" cut/paste
    Document * document = [NSApp targetForAction: @selector(firstTextView)];
    [[document firstTextView] setSmartInsertDeleteEnabled: NO];
}

//- (id)init{
//   return [super self];
//}

- (IBAction)wordcount:(id)source{
    Document * document = [NSApp targetForAction: @selector(firstTextView)];
    int spell_wc = [self _wordCountWithSpellChecker: [[document textStorage] string]];
    int selected_wc = [self _wordCountWithSpellChecker: [self _selectedTextFromTextView: [document firstTextView]]];
    NSString * report;
    if (selected_wc){
        report = [NSString stringWithFormat: @"%d words in document\n%d words in selection", spell_wc, selected_wc];
    }else{
        report = [NSString stringWithFormat: @"%d words", spell_wc];
    }
    NSBeginInformationalAlertSheet(@"Word Count", nil, nil, nil, [NSApp keyWindow],
        nil, nil, nil, nil, report);
}

- (int)_wordCountWithSpellChecker: (NSString *)string{
    return [[NSSpellChecker sharedSpellChecker] countWordsInString: string language: nil];
}

- (NSString *)_selectedTextFromTextView: (NSTextView *) textview{
    NSArray * ranges = [textview selectedRanges];
    if (([ranges count] == 1) && (! [[ranges objectAtIndex: 0] rangeValue].length)){
        return @"";
    }
    NSMutableArray * selections = [NSMutableArray arrayWithCapacity: [ranges count]];
    NSString * string = [textview string];
    int i;
    for (i = 0; i < [ranges count]; i++){
        [selections addObject: [string substringWithRange: [[ranges objectAtIndex: i] rangeValue]]];
    }
    return [selections componentsJoinedByString: @" "];
}

@end
